//
//  BHBDrawer.m
//  公考神器
//
//  Created by 毕武侠 on 16/5/18.
//  Copyright © 2016年 毕武侠. All rights reserved.
//

#import "BHBDrawer.h"
#import "BHBPaintPath.h"

@interface BHBDrawer ()

@property (nonatomic, strong) BHBPaintPath * path;
@property (nonatomic, strong) CAShapeLayer * slayer;
/**
 *  存放所有移动过程中的点(包括起始点)
 */
@property (nonatomic, strong) NSMutableArray *moveLines;

@end

@implementation BHBDrawer

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _width   = 3;
        _isFirst = [NSNumber numberWithBool:YES];
        _isLast  = [NSNumber numberWithBool:YES];
    }
    return self;
}

- (NSMutableArray *)moveLines {
    if (!_moveLines) {
        _moveLines = [NSMutableArray array];
    }
    return _moveLines;
}

// 根据touches集合获取对应的触摸点
- (CGPoint)pointWithTouches:(NSSet *)touches {
    UITouch *touch = [touches anyObject];
    return [touch locationInView:self];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint startP = [self pointWithTouches:touches];
    
    if ([event allTouches].count == 1) {
        _path = [BHBPaintPath paintPathWithLineWidth:_width
                                          startPoint:startP];
        CAShapeLayer * slayer   = [CAShapeLayer layer];
        slayer.path             = _path.CGPath;
        slayer.backgroundColor  = [UIColor clearColor].CGColor;
        slayer.fillColor        = [UIColor clearColor].CGColor;
        slayer.lineCap          = kCALineCapRound;
        slayer.lineJoin         = kCALineJoinRound;
        slayer.strokeColor      = [UIColor blackColor].CGColor;
        slayer.lineWidth        = _path.lineWidth;
        [self.layer addSublayer:slayer];
        _slayer = slayer;
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取移动点
    CGPoint moveP = [self pointWithTouches:touches];
    if ([event allTouches].count > 1) {
        [self.superview touchesMoved:touches withEvent:event];
    } else if ([event allTouches].count == 1) {
        [_path addLineToPoint:moveP];
        _slayer.path = _path.CGPath;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if ([event allTouches].count > 1){
        [self.superview touchesMoved:touches withEvent:event];
    }
    
    if (self.model.allPointsArr.count > 0 && self.model.curIndex < self.model.allPointsArr.count) {
        [self.model.allPointsArr removeObjectsInRange:NSMakeRange(self.model.curIndex , self.model.allPointsArr.count - self.model.curIndex)];
    }
    
    if ([self.model.startPointsArr.lastObject integerValue] > self.model.startIndex) {
        __block NSUInteger clearIndex = 0;
        [self.model.startPointsArr enumerateObjectsUsingBlock:^(NSNumber *start, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([start integerValue] >= self.model.curIndex) {
                clearIndex = idx;
                *stop = YES;
            }
        }];
        
        [self.model.startPointsArr removeObjectsInRange:NSMakeRange(clearIndex + 1, self.model.startPointsArr.count - clearIndex - 1)];
    }
    
    self.isLast = [NSNumber numberWithBool:YES];
    self.isFirst = [NSNumber numberWithBool:NO];
    [self.moveLines addObject:_slayer];
    [self.model.allPointsArr addObject:_slayer];
    
    self.model.curIndex++;
}

- (void)setModel:(PaletteModel *)model {
    if(_model == model) return;
    
    _model = model;
    
    [self clearLayers];
    [self drawLine];
}

- (void)drawLine {
    if (self.model.allPointsArr.count == 0 ) {
        return;
    }
    if (self.model.curIndex > self.model.allPointsArr.count) {
        self.model.curIndex = self.model.allPointsArr.count;
    }
    
    for (NSInteger i = self.model.startIndex; i < self.model.curIndex; i++) {
        
        CAShapeLayer *slayer = [self.model.allPointsArr objectAtIndex:i];
        // 调用画线方法
        [self.layer addSublayer:slayer];
    }
}

- (void)clearLayers {
    NSMutableArray *shapeLayers = [NSMutableArray array];
    [self.layer.sublayers enumerateObjectsUsingBlock:^(CALayer *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[CAShapeLayer class]]) {
            [shapeLayers addObject:obj];
        }
    }];
    
    [shapeLayers enumerateObjectsUsingBlock:^(CALayer *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperlayer];
    }];
    
    [self.moveLines removeAllObjects];
}

- (void)clear {
    if (self.model.curIndex == self.model.startIndex) {
        return;
    }
    
    __block NSUInteger clearIndex = 0;
    [self.model.startPointsArr enumerateObjectsUsingBlock:^(NSNumber *start, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([start integerValue] >= self.model.curIndex) {
            clearIndex = idx;
            *stop = YES;
        }
    }];
    
    
    if (clearIndex != 0) {
        [self.model.startPointsArr removeObjectsInRange:NSMakeRange(clearIndex , self.model.startPointsArr.count - clearIndex)];
    }
    
    [self.model.startPointsArr addObject:[NSNumber numberWithInteger:self.model.curIndex]];

    [self.model.allPointsArr removeObjectsInRange:NSMakeRange(self.model.curIndex, self.model.allPointsArr.count - self.model.curIndex)];

    self.model.startIndex = self.model.curIndex;
    [self clearLayers];
}

- (void)next {
    if (self.model.curIndex > self.model.allPointsArr.count) {
        self.isLast = [NSNumber numberWithBool:YES];
        return;
    }
    
    self.model.curIndex++;
    if ([self.model.startPointsArr.lastObject integerValue] != self.model.startIndex) {
        __block NSInteger curStartIndex = 0;
        [self.model.startPointsArr enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj integerValue] == self.model.startIndex) {
                curStartIndex = idx;
                *stop = YES;
            }
        }];
        
        if ([self.model.startPointsArr[curStartIndex + 1] integerValue] < self.model.curIndex) {
            self.model.startIndex = [self.model.startPointsArr[curStartIndex + 1] integerValue];
            self.model.curIndex--;
        }
    }
    
    if (self.model.curIndex == self.model.allPointsArr.count) {
        self.isLast = [NSNumber numberWithBool:YES];
    } else if ([self.isLast boolValue] != NO) {
        self.isLast = [NSNumber numberWithBool:NO];
    }
    
    if (self.model.curIndex > 0 && [self.isFirst boolValue] != NO) {
        self.isFirst = [NSNumber numberWithBool:NO];
    }
    // 要改
    [self clearLayers];
    [self drawLine];
}

- (void)last {
    if (self.model.curIndex <= 0) {
        self.isFirst = [NSNumber numberWithBool:YES];
        return;
    }
    
    self.model.curIndex--;
    if (self.model.curIndex < self.model.startIndex) {
        __block NSUInteger curStartIndex = 0;
        [self.model.startPointsArr enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (self.model.startIndex == [obj integerValue]) {
                curStartIndex = idx;
                *stop = YES;
            }
        }];
        
        if (curStartIndex > 0) {
            NSUInteger startIndex = [self.model.startPointsArr[curStartIndex - 1] integerValue];
            self.model.startIndex = startIndex;
            self.model.curIndex++;
        }
    }
    
    if ([self.isFirst boolValue] != NO) {
        self.isFirst = [NSNumber numberWithBool:NO];
    }
    if (self.model.curIndex < self.model.allPointsArr.count && [self.isLast boolValue] != NO) {
        self.isLast = [NSNumber numberWithBool:NO];
    }

    // 要改
    [self clearLayers];
    [self drawLine];
}

@end
